﻿using Aspfm.Main;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AspfmHttpServer
{
    public partial class AspfmHttp : Form
    {
        private decimal LastExeTime = 0;
        private int isAutoExit = 0;
        public AspfmHttp()
        {
            InitializeComponent();

            checkBox1.Checked = AspfmTool.IsRunWhenStart(Application.ProductName);


            button1.Enabled = false;
            LastExeTime = Convert.ToDecimal(DateTime.Now.ToString("yyyyMMddHHmmss"));

            Timer aTimer = new System.Windows.Forms.Timer();
            aTimer.Interval = 1000;
            //注册计时器的事件
            aTimer.Tick += aTimer_Tick;
            aTimer.Start();

            dataGridView1.RowStateChanged += dataGridView1_RowStateChanged;

            notifyIcon1_MouseDoubleClick(null,null);
        }

        void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
            e.Row.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
        }
        public AspfmHttp(string date,string port)
        {
            InitializeComponent();

            button1.Enabled = false;

            Timer aTimer = new System.Windows.Forms.Timer();
            aTimer.Interval = 1000;
            //注册计时器的事件
            aTimer.Tick += aTimer_Tick;
            aTimer.Start();


            int datehour = 0;
            int.TryParse(date, out datehour);
            int tempport = 0;
            int.TryParse(port, out tempport);

            numericUpDown2.Value = datehour;
            numericUpDown1.Value = tempport;
            button2_Click(null,null);
        }

        void aTimer_Tick(object sender, EventArgs e)
        {
            dateTimePicker1.Value = dateTimePicker2.Value = DateTime.Now;
            ExeFiles();
            ReStartHttpServer();
        }

        private void ReStartHttpServer()
        {
            if (dateTimePicker1.Value.Hour == numericUpDown2.Value && dateTimePicker1.Value.Minute == 0 && dateTimePicker1.Value.Second == 0)
            //if (dateTimePicker1.Value.Second == 0)
            {
                if (button1.Enabled)
                {
                    try
                    {
                        ProcessStartInfo psi = new ProcessStartInfo();
                        psi.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
                        psi.FileName = "AspfmHttpServer.exe";
                        psi.Arguments = numericUpDown2.Value + "  " + numericUpDown1.Value;
                        psi.UseShellExecute = false;
                        psi.CreateNoWindow = true;
                        Process.Start(psi);
                        System.Threading.Thread.Sleep(1000);
                        isAutoExit = 999;
                        Application.Exit();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("AspfmHttpServer.exe重启失败。失败原因：" + ex.Message + ex.StackTrace);
                    }
                }
            }
        }

        static HttpListener listener = null;

        private void button2_Click(object sender, EventArgs e)
        {
            if (!HttpListener.IsSupported)
            {
                MessageBox.Show("当前系统不支持HttpListener。");
                return;
            }
            if (numericUpDown1.Value > 0)
            {
                string aspfmpath = Aspfm.Main.BaseAshx.CurrentPath() + "\\Aspfm.Server";
                if (System.IO.Directory.Exists(aspfmpath))
                {
                    MessageBox.Show("目录上不允许包含Aspfm.Server文件夹。");
                    return;
                }
                if (listener == null)
                {
                    try
                    {
                        listener = new HttpListener();
                        var url = "http://+:" + numericUpDown1.Value + "/Aspfm.Server/";
                        listener.Prefixes.Add(url);
                        listener.Start();
                        listener.BeginGetContext(MainProcess, null);

                        button1.Enabled = true;
                        button2.Enabled = false;
                        textBox1.Text = "http://127.0.0.1:" + numericUpDown1.Value + "/Aspfm.Server/Aspfm";
                    }
                    catch (Exception ex)
                    {
                        try {
                            listener.Close();
                            listener = null;
                        }
                        catch { }
                        MessageBox.Show(ex.Message);
                    }
                };
            }
            else
            {
                MessageBox.Show("请输入端口号。");
            }
        }
        private static void MainProcess(IAsyncResult ar)
        {
            try
            {
                HttpListenerContext context = listener.EndGetContext(ar);
                listener.BeginGetContext(MainProcess, null);
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    try
                    {
                        Aspfm.Main.BaseAshx.AspfmRequest(context);
                        if (context.Response.ContentLength64 == 0 || string.IsNullOrEmpty(context.Response.ContentType))
                        {
                            Aspfm.Main.BaseAshx.ReturnHtml("", null, context);
                        }
                    }
                    catch (Exception ex)
                    {
                        Aspfm.Main.Loger.WriteLog(ex);
                        Aspfm.Main.BaseAshx.ReturnHtml(ex.Message + ex.StackTrace, null, context);
                    }
                    //var response = context.Response;
                    //response.AddHeader("Server", "Aspfm Server V0.0.1");
                    //var request = context.Request;
                    //var path = request.Url.LocalPath;
                    //if (path.StartsWith("/") || path.StartsWith("\\"))
                    //    path = path.Substring(1);
                    //var sb = new StringBuilder("输入请求:");
                    //sb.AppendLine(path);
                    //var visit = path.Split(new char[] { '/', '\\' }, 2);
                    //if (visit.Length > 0)
                    //{
                    //    var cmd = visit[0].ToLower();
                    //    sb.AppendLine(string.Format("执行命令:{0}", cmd));
                    //    sb.AppendLine(string.Format("另外有{0}个参数", visit.Length - 1 + request.QueryString.Count));
                    //}
                    //sb.AppendLine(DateTime.Now.ToString());
                    //response.ContentType = "text/plain;charset=UTF-8";
                    //var result = Encoding.UTF8.GetBytes(sb.ToString());
                    //using (var stream = response.OutputStream)
                    //{
                    //    stream.Write(result, 0, result.Length);
                    //}
                });
            }
            catch { }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (listener != null)
            {
                try
                {
                    listener.Close();
                    listener = null;

                    textBox1.Text = "";
                    button2.Enabled = true;
                    button1.Enabled = false;
                }
                catch { }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            dataGridView1.EndEdit();
            AspfmServer aspfmserver = new AspfmServer();
            aspfmserver.exeTime = numericUpDown3.Value;
            foreach (DataGridViewRow dr in dataGridView1.Rows)
            {
                if (dr.Cells[0].Value != null)
                {
                    aspfmserver.exeFileList.Add(dr.Cells[0].Value.ToString().Trim());
                }
            }
            Aspfm.Main.SerializeHelper.Save(aspfmserver, GetAspfmServerXml());
        }

        internal static string GetAspfmServerXml()
        {
            string xmlpath = Directory.GetParent(BaseAshx.CurrentPath(true).Trim('\\').Trim('/')).FullName;
            return xmlpath + "\\AspfmServer.xml";
        }

        private void AspfmHttp_Load(object sender, EventArgs e)
        {
            if (System.IO.File.Exists(GetAspfmServerXml()))
            {
                try
                {
                    AspfmServer aspfmserver = Aspfm.Main.SerializeHelper.Load(typeof(AspfmServer), GetAspfmServerXml()) as AspfmServer;
                    if (aspfmserver != null)
                    {
                        numericUpDown3.Value = aspfmserver.exeTime;
                        foreach (string str in aspfmserver.exeFileList)
                        {
                            dataGridView1.Rows.Add(str);
                        }
                    }
                }
                catch { }
            }
        }
        private void ExeFiles()
        {
            decimal timestr = Convert.ToDecimal(DateTime.Now.AddMinutes(-(int)numericUpDown3.Value).ToString("yyyyMMddHHmmss"));
            if (timestr > LastExeTime)
            {
                WriteLog("开始执行AspfmServerAutomatic");
                LastExeTime = Convert.ToDecimal(DateTime.Now.ToString("yyyyMMddHHmmss"));
                label9.Text = "上次执行时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                foreach (DataGridViewRow dr in dataGridView1.Rows)
                {
                    if (dr.Cells[0].Value != null)
                    {
                        string strfile = dr.Cells[0].Value.ToString();
                        if (!System.IO.File.Exists(strfile))
                        {
                            strfile = BaseAshx.CurrentPath(true) + strfile;
                        }
                        if (File.Exists(strfile))
                        {
                            try
                            {
                                ProcessStartInfo psi = new ProcessStartInfo();
                                psi.WorkingDirectory = Path.GetDirectoryName(strfile);
                                psi.FileName = Path.GetFileName(strfile);
                                psi.Arguments = "\"AspfmServerAutomatic\"";
                                psi.UseShellExecute = false;
                                psi.CreateNoWindow = true;
                                Process.Start(psi);
                            }
                            catch (Exception ex)
                            {
                                string loger = "应用程序：" + strfile+"   执行报错。错误信息：\r\n";
                                loger += ex.Message;
                                WriteLog(loger);
                            }
                        }
                        else
                        {
                            string loger = "找不到应用程序：" + strfile;
                            WriteLog(loger);
                        }
                    }
                }
            }
        }
        private void WriteLog(string msg)
        {
            Loger.WriteLog(LogType.AspfmServers, msg, "");
            txtLoger.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "      " + msg + "\r\n" + txtLoger.Text;
            if (txtLoger.Text.Length > 10000)
            {
                txtLoger.Text = txtLoger.Text.Substring(0, 10000);
            }
        }

        private void AspfmHttp_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isAutoExit == 999)
            {
                return;
            }
            else
            {
                this.WindowState = FormWindowState.Minimized;
                this.Hide();
                e.Cancel = true;
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (checkBox1.Checked)
                {
                    AspfmTool.RunWhenStart(true, Application.ProductName, Application.StartupPath + "\\AspfmHttpServer.exe");
                }
                else
                {
                    AspfmTool.RunWhenStart(false, Application.ProductName, Application.StartupPath + "\\AspfmHttpServer.exe");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                this.WindowState = FormWindowState.Minimized;
                this.Hide();
            }
            else if (this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
        }

        private void showMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }

        private void hideMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void exitMenuItem_Click(object sender, EventArgs e)
        {
            isAutoExit = 999;
            Application.Exit();
        }

        private void AspfmHttp_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide(); //或者是this.Visible = false;
                this.notifyIcon1.Visible = true;
            }
        }
    }
}
